﻿
using Kele.Core.Extensions.DependencyInjection;
using Kele.Activity.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Reflection;

namespace Kele.Activity
{
    public static class Register
    {
        public static IServiceCollection AddKeleActivityServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env)
        {
            services.Configure<ActivitySetting>(configuration.GetSection("KeleActivitySetting"));

           // var entryAssembly = Assembly.GetExecutingAssembly();
            //var assemblies = new List<Assembly> { entryAssembly }.Concat(entryAssembly.GetReferencedAssemblies().Select(Assembly.Load));

            //var settingsManager = new SettingsManager(configuration, env.ContentRootPath, env.WebRootPath, entryAssembly);
            //services.TryAdd(ServiceDescriptor.Singleton<ISettingsManager>(settingsManager));
          
            //services.AddCache(settingsManager.Redis.ConnectionString);
            //services.AddRepositories(assemblies);
           // services.AddServices();

            return services;
        }

        public static void AddRepositories(this IServiceCollection services, IEnumerable<Assembly> assemblies)
        {
            //var baseType = typeof(IRepository);

            //var types = assemblies
            //    .SelectMany(a => a.DefinedTypes)
            //    .Select(type => type.AsType())
            //    .Where(x => x != baseType && baseType.IsAssignableFrom(x)).ToArray();
            //var implementTypes = types.Where(x => x.IsClass).ToArray();
            //var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
            //foreach (var implementType in implementTypes)
            //{
            //    var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
            //    if (interfaceType != null)
            //    {
            //        //if (interfaceType == typeof(IContentRepository)) continue;

            //        services.AddScoped(interfaceType, implementType);
            //    }
            //}
        }

        public static void AddServices(this IServiceCollection services)
        {
            
          //  services.AddScoped<IFormService, FormService>();
        }

        public static IApplicationBuilder UseKeleActivity(this IApplicationBuilder app, ActivitySetting keleActivitySetting)
        {
            var provider = app.ApplicationServices;
            var logger = provider.GetLogger("Kele.Activity Register");
            logger.LogInformation(0, "框架初始化开始");
            AppConfig.Setting = keleActivitySetting;
            Kele.Repository.Config.DefaultConnectionString= keleActivitySetting.DefaultConnectionString;
            return app;
        }

        public static void AddCache(this IServiceCollection services, string redisConnectionString)
        {
            //services.AddCacheManagerConfiguration(async settings =>
            //{
            //    var isBackPlane = false;
            //    if (!string.IsNullOrEmpty(redisConnectionString))
            //    {
            //        var redis = new Redis(redisConnectionString);
            //        var (isConnectionWorks, _) = await redis.IsConnectionWorksAsync();
            //        if (isConnectionWorks)
            //        {
            //            settings
            //                .WithMicrosoftMemoryCacheHandle()
            //                .WithExpiration(ExpirationMode.None, TimeSpan.Zero)
            //                .And
            //                .WithRedisConfiguration("redis", config =>
            //                {
            //                    if (!string.IsNullOrEmpty(redis.Password))
            //                    {
            //                        config.WithPassword(redis.Password);
            //                    }
            //                    if (redis.AllowAdmin)
            //                    {
            //                        config.WithAllowAdmin();
            //                    }

            //                    config
            //                        .WithDatabase(redis.Database)
            //                        .WithEndpoint(redis.Host, redis.Port);
            //                })
            //                .WithMaxRetries(1000)
            //                .WithRetryTimeout(100)
            //                .WithJsonSerializer()
            //                .WithRedisBackplane("redis")
            //                .WithRedisCacheHandle("redis");

            //            isBackPlane = true;
            //        }
            //    }

            //    if (!isBackPlane)
            //    {
            //        settings
            //            .WithMicrosoftMemoryCacheHandle()
            //            .WithExpiration(ExpirationMode.None, TimeSpan.Zero);
            //    }
            //});
            //services.AddCacheManager();
        }
    }
}